package lyh.hnu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import lyh.hnu.common.R;
import lyh.hnu.entity.po.Employee;
import lyh.hnu.mapper.EmployeeMapper;
import lyh.hnu.service.EmployeeService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService{
    @Override
    public R<Employee> login(HttpServletRequest request, Employee employee) {
        String username = employee.getUsername();
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        Employee requiredEmp = lambdaQuery().eq(Employee::getUsername, username).one();
        if (requiredEmp == null) {
            return R.error("登录失败，请重新登录");
        }
        if (!requiredEmp.getPassword().equals(password)) {
            return R.error("登录失败，请重新登录");
        }
        if (requiredEmp.getStatus() == 0) {
            return R.error("账户已禁用");
        }
        request.getSession().setAttribute("employee", requiredEmp.getId());
        return R.success(requiredEmp);
    }

    @Override
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("账户已推出");
    }

    @Override
    public R<String> saveEmp(HttpServletRequest request, Employee employee) {
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());

        //long empId = (Long) request.getSession().getAttribute("employee");
        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);
        save(employee);
        return R.success("新增员工成功");
    }
}
